package com.szjlc.blog.common.result;

import com.szjlc.blog.common.utils.TraceIdUtil;
import java.text.SimpleDateFormat;
import java.util.Date;
import lombok.Data;

/**
 * 统一返回结果
 *
 * @author steve
 * @since 2022-11-13 15:14
 */
@Data
public class WebServiceResponse<T> {

    /** 响应码 */
    private Integer code;

    /** 响应信息 */
    private String message;

    /** 响应数据 */
    private T data;

    /** 链路追踪id */
    private String traceId;

    /** 时间戳 */
    private String timeStamp;


    public static final SimpleDateFormat FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:S");

    public static <T> WebServiceResponse<T> success(T data) {
        return success(200, "操作成功", data, new Date());
    }

    private static <T> WebServiceResponse<T> success(Integer code, String message, T data, Date date) {
        WebServiceResponse<T> result = new WebServiceResponse<>();
        result.setCode(code);
        result.setMessage(message);
        result.setData(data);
        result.setTraceId(TraceIdUtil.getTraceId());
        result.setTimeStamp(FORMAT.format(date));
        return result;
    }

    public static <T> WebServiceResponse<T> fail(Integer code, String message) {
        return fail(code, message, null, new Date());
    }

    public static <T> WebServiceResponse<T> fail(String message) {
        return fail(401, message, null, new Date());
    }

    private static <T> WebServiceResponse<T> fail(Integer code, String message, T data, Date date) {
        WebServiceResponse<T> result = new WebServiceResponse<>();
        result.setCode(code);
        result.setMessage(message);
        result.setData(data);
        result.setTraceId(TraceIdUtil.getTraceId());
        result.setTimeStamp(FORMAT.format(date));

        return result;
    }


}
